import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { Auths, Role } from '@/utils/types.d';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, message, Tag } from 'antd';
import confirm from 'antd/lib/modal/confirm';
import moment from 'moment';
import { useEffect, useState } from 'react';
import { useModel } from 'umi';
// import { Tag } from 'antd';
import { getTotalArrear, queryArrears, sendArrearMessage } from '../service';
import type { ArrearsTableItem } from '../types.d';
// const mapColor = new Map()
//   .set(0, '#839bac')
//   .set(1, '#108ee9')
//   .set(2, '#faad14')
//   .set(3, 'default')
//   .set(4, 'black')
//   .set(5, '#70c04e');
export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.arrearsRecovery || []) : new Set();
  const ifModify = auths.has(Auths.MODIFY);
  const [time, setTime] = useState<string>();
  const [totalArrear, setTotalArrear] = useState<number>(0);
  const columns: ProColumns<ArrearsTableItem>[] = [
    {
      title: '车牌号码',
      dataIndex: 'plateNumber',
      align: 'center',
      // render: (_, record) => {
      //   const { plateColor, plateNumber } = record;
      //   if (plateColor && plateColor?.length > 0) {
      //     const color = mapColor.get(plateColor[plateColor?.length - 1 || 0]);
      //     return (
      //       <Tag style={{ width: '85px', fontWeight: 'bolder', margin: '0 auto' }} color={color}>
      //         {plateNumber}
      //       </Tag>
      //     );
      //   }

      //   return (
      //     <Tag
      //       style={{ width: '85px', fontWeight: 'bolder', margin: '0 auto' }}
      //       color={mapColor.get(0)}
      //     >
      //       {plateNumber}
      //     </Tag>
      //   );
      // },
    },
    {
      title: '车牌颜色',
      dataIndex: 'plateColor',
      hideInSearch: true,
      align: 'center',
      renderText: (plateColor) => {
        if (plateColor && plateColor?.length > 0) {
          return plateColor[plateColor?.length - 1 || 0];
        }
        return 0;
      },
      valueEnum: {
        0: { text: '未知' },
        1: { text: '蓝' },
        2: { text: '黄' },
        3: { text: '白' },
        4: { text: '黑' },
        5: { text: '绿' },
        6: { text: '黄绿' },
      },
    },
    {
      title: '欠费总金额',
      dataIndex: 'arrears',
      hideInSearch: true,
      align: 'center',
      valueType: 'money',
      sorter: true,
      renderText: (t) => t / 100,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      align: 'center',
      valueType: 'dateTime',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      hideInSearch: true,
      align: 'center',
      valueType: 'dateTime',
    },
    {
      title: '车主',
      dataIndex: ['wechatUser', 'nickname'],
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '车主手机号',
      dataIndex: ['wechatUser', 'phone'],
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '是否绑定微信用户',
      hideInSearch: true,
      align: 'center',
      dataIndex: 'wechatUser',
      renderText: (wechatUser) => {
        if (wechatUser) return 'yes';
        return 'no';
      },
      valueEnum: {
        yes: { text: '是', status: 'success' },
        no: { text: '否', status: 'error' },
      },
    },
    {
      title: '短信通知时间',
      dataIndex: 'lastNotifyTime',
      hideInSearch: true,
      align: 'center',
      valueType: 'dateTime',
    },

    // {
    //   title: '欠费次数',
    //   dataIndex: 'count',
    //   hideInSearch: true,
    //   align: 'center',
    //   renderText: (text) => `${text}次`,
    // },
    {
      title: '操作',
      fixed: 'right',
      valueType: 'option',
      hideInSearch: true,
      align: 'center',
      render: (_, record) => {
        return ifModify
          ? [
              record.wechatUser ? (
                <Button
                  type="primary"
                  onClick={() => {
                    confirm({
                      title: '操作确认',
                      icon: <ExclamationCircleOutlined style={{ color: '#ffa940' }} />,
                      content: (
                        <span>
                          是否确认向车牌号为
                          <Tag style={{ fontWeight: 900 }}>{record?.plateNumber}</Tag>, 手机号为
                          {record?.wechatUser?.phone}的用户发送缴费短信?
                        </span>
                      ),
                      okText: '发送',
                      cancelText: '取消',
                      onOk() {
                        return sendArrearMessage({
                          plateNumber: record?.plateNumber,
                          phone: record?.wechatUser?.phone,
                          arrears: record?.arrears,
                          id: record?._id,
                        }).then((res) => {
                          if (res.success) {
                            message.success({ content: res.message, key: 'send' });
                          } else {
                            message.error({ content: res.message, key: 'send' });
                          }
                        });
                      },
                    });
                  }}
                >
                  发送短信
                </Button>
              ) : (
                <PlaceHolderCpn text="未绑定手机" />
              ),
            ]
          : [<PlaceHolderCpn key={record?.plateNumber} />];
      },
    },
  ];
  useEffect(() => {
    const queryParams: { ownerId?: string } = {};
    if (currUser?.role != Role.ADMIN) queryParams.ownerId = currUser?.ownerId;
    getTotalArrear(queryParams).then((res) => {
      if (res.success) {
        setTime(moment().format('YYYY-MM-DD HH:mm:ss'));
        setTotalArrear(res.data);
        return;
      }
      message.warn({ content: '历史欠费金额获取失败', key: 'totalArrear' });
    });
  }, []);
  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: '欠费列表',
        breadcrumb: {
          routes: [
            { path: '/', breadcrumbName: '首页' },
            { path: '/arrears-recovery', breadcrumbName: '欠费追缴' },
            { path: '/arrears-recovery/arrears', breadcrumbName: '欠费列表' },
          ],
        },
      }}
    >
      <ProTable<ArrearsTableItem>
        rowKey="plateNumber"
        columns={columns}
        headerTitle={`历史总欠费金额${(totalArrear / 100).toFixed(2)}元，统计截至时间：${time}`}
        scroll={{ x: true }}
        style={{ whiteSpace: 'nowrap' }}
        columnEmptyText="暂无数据"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        search={{
          labelWidth: 'auto',
        }}
        debounceTime={300}
        request={async (param, sort) => {
          const res = await queryArrears(param, sort);
          return res;
        }}
      />
    </PageHeaderWrapper>
  );
};
